package com.example.administrator.xiaoxiang.fragment;


import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.example.administrator.xiaoxiang.R;
import com.example.administrator.xiaoxiang.activity.SearchActivity;
import com.example.administrator.xiaoxiang.activity.ShopCardActivity;
import com.example.administrator.xiaoxiang.adapter.HomeFragmentAdapter;
import com.example.administrator.xiaoxiang.entity.ShopingcartEntity;
import com.example.administrator.xiaoxiang.fragment.homedetailfragment.HomeFifthFragment;
import com.example.administrator.xiaoxiang.fragment.homedetailfragment.HomeFirstFragment;
import com.example.administrator.xiaoxiang.fragment.homedetailfragment.HomeFourthFragment;
import com.example.administrator.xiaoxiang.fragment.homedetailfragment.HomeSecondFragment;
import com.example.administrator.xiaoxiang.fragment.homedetailfragment.HomeSeventhFragment;
import com.example.administrator.xiaoxiang.fragment.homedetailfragment.HomeSixthFragment;
import com.example.administrator.xiaoxiang.fragment.homedetailfragment.HomeThirdFragment;
import com.example.administrator.xiaoxiang.gen.DaoMaster;
import com.example.administrator.xiaoxiang.gen.DaoSession;
import com.example.administrator.xiaoxiang.gen.ShopingcartEntityDao;
import com.example.administrator.xiaoxiang.url.URLResource;
import com.example.administrator.xiaoxiang.utils.AsyncTaskHelper;
import com.example.administrator.xiaoxiang.widget.BaseHomeViewPager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * 首页fragment
 */
public class HomeFragment extends Fragment implements AsyncTaskHelper.OnDataDownloadListener,View.OnClickListener{
    public static final String TAG = "HomeFragment";
    private TabLayout tabLayout;
    private BaseHomeViewPager viewPager;//由于会出现拦截冲突问题而自定义viewPager
    private List<Fragment> data;
    private List<String> arrs;//用于存储tablayout的数据
    private AsyncTaskHelper helper;
    private TextView textView;//上方的搜索
    private HomeFragmentAdapter homeFragmentAdapter;
    private FrameLayout frameLayout;//购物车
    private int count = 0;//购物车物品的数量
    private TextView count_textView;
    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        init(view);
        loadData();
        viewPager.setCurrentItem(0);
        textView.setOnClickListener(this);
        frameLayout.setOnClickListener(this);
        return view;
    }

    private void initDb() {
        DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(getContext().getApplicationContext(), "XX.db", null);
        SQLiteDatabase db = openHelper.getReadableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        ShopingcartEntityDao shopingcartEntityDao = daoSession.getShopingcartEntityDao();
        List<ShopingcartEntity> list =
                shopingcartEntityDao.queryBuilder().build().list();
        for (ShopingcartEntity shopingcartEntity : list) {
            count+=Integer.parseInt(shopingcartEntity.getNum());
        }
    }

    private void loadData() {
        HomeFirstFragment first = new HomeFirstFragment();
        HomeSecondFragment second = new HomeSecondFragment();
        HomeThirdFragment third = new HomeThirdFragment();
        HomeFourthFragment fourth = new HomeFourthFragment();
        HomeFifthFragment fifth = new HomeFifthFragment();
        HomeSixthFragment sixth = new HomeSixthFragment();
        HomeSeventhFragment seventh  = new HomeSeventhFragment();
        data.add(first);
        data.add(second);
        data.add(third);
        data.add(fourth);
        data.add(fifth);
        data.add(sixth);
        data.add(seventh);
        helper = new AsyncTaskHelper();
        helper.downloadData(URLResource.HomeTabURL, this);
    }

    private void setTabLayoutListener() {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition()!=arrs.size()) {
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void init(View view) {

        tabLayout = (TabLayout) view.findViewById(R.id.tabLayout_home_fragment);
        textView = (TextView) view.findViewById(R.id.text_home_fragment);
        frameLayout = (FrameLayout) view.findViewById(R.id.shop_cart);
        count_textView = (TextView) view.findViewById(R.id.circle);
        viewPager = (BaseHomeViewPager) view.findViewById(R.id.viewPager_home_fragment);
        //初始化tablayout
        tabLayout.setTabTextColors(Color.BLACK,Color.RED);
        //设置小滑块的高度
        tabLayout.setSelectedTabIndicatorHeight(5);
        //设置小滑块的颜色
        tabLayout.setSelectedTabIndicatorColor(Color.RED);
        data = new ArrayList<>();
        arrs = new ArrayList<>();
//        homeFragmentAdapter = new HomeFragmentAdapter(getChildFragmentManager(),data,arrs);
//        viewPager.setAdapter(homeFragmentAdapter);

    }

    //执行完成异步任务的回调接口
    @Override
    public void onDataDownload(byte[] result) {
        String json  = new String(result);
//                Log.e(TAG, "onDataDownload: "+json);
        arrs = parseJson(json);
        homeFragmentAdapter = new HomeFragmentAdapter(getChildFragmentManager(),data,arrs);
        viewPager.setAdapter(homeFragmentAdapter);
        tabLayout.setupWithViewPager(viewPager);
        setTabLayoutListener();
    }
    //json数据的解析
    private List<String> parseJson(String json) {
        List<String> titles = new ArrayList<String>();
        try {
            JSONObject object1 = new JSONObject(json);
            JSONObject body = object1.getJSONObject("body");
            JSONArray list = body.getJSONArray("pageViews");
//                    Log.e(TAG, "parseJson: "+list.toString());
            for (int i = 0; i < list.length(); i++) {
                JSONObject object = list.getJSONObject(i);
                String titleName = object.getString("titleName");
//                        Log.e(TAG, "parseJson: "+title);
                titles.add(titleName);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return titles;
    }

    //上方搜素界面的监听
    @Override
    public void onClick(View v) {
//        Toast.makeText(getContext(), "dianjile", Toast.LENGTH_SHORT).show();
        Intent intent;
        if (v instanceof TextView) {
            intent= new Intent(getContext(), SearchActivity.class);
            startActivity(intent);
        }else if(v instanceof FrameLayout){
            intent = new Intent(getContext(), ShopCardActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        count = 0;
        initDb();
        if (count==0) {
            count_textView.setVisibility(View.GONE);
        }else{
            count_textView.setVisibility(View.VISIBLE);
            count_textView.setText(count+"");
        }
    }

}
